﻿using Microsoft.EntityFrameworkCore;
using Oracle.ManagedDataAccess.Client;
using WMS.FC.Domain.DomainObject.System;
using WMS.FC.Domain.PersistenceObject.Business;
using WMS.FC.Domain.Repository;
using WMS.FC.Infrastructure.Common;

namespace WMS.FC.Infrastructure.Repository
{
    public class TrayRepository : RepositoryBase, ITrayRepository
    {
        public TrayRepository(WmsDbContext dbContext) : base(dbContext)
        {
        }

        public async Task<TrayPO?> GetTrayByBarcode(string trayBarcode)
        {
            return await dbContext.Set<TrayPO>().AsNoTrackingWithIdentityResolution().FirstOrDefaultAsync(entity => entity.Barcode == trayBarcode);
        }

        public async Task<List<TrayPO>> GetTrayListByBarcode(string trayBarcode)
        {
            return await dbContext.Set<TrayPO>().AsNoTrackingWithIdentityResolution().Where(entity => entity.ContainerBarcode == trayBarcode).ToListAsync();
        }

        public async Task<List<CellPO>> GetTrayCellList(string trayBarcode)
        {
            return await dbContext.Set<CellPO>().AsNoTrackingWithIdentityResolution().Where(entity => entity.TrayBarcode == trayBarcode).ToListAsync();
        }

        public async Task<int> UnpileTray(string containerBarcode, UserInfo userInfo)
        {
            return await dbContext.Database.ExecuteSqlRawAsync(@"UPDATE B_TRAY T
   SET T.CONTAINER_BARCODE = T.BARCODE,
       T.TRAY_POSITION     = 1,
       T.MODIFY_DATE       = :MODIFY_DATE,
       T.MODIFIED_BY       = :MODIFIED_BY,
       T.MODIFY_IP         = :MODIFY_IP
 WHERE CONTAINER_BARCODE = :CONTAINER_BARCODE", new List<OracleParameter>() {
                new OracleParameter("CONTAINER_BARCODE", containerBarcode),
                new OracleParameter("MODIFY_DATE", DateTime.Now),
                new OracleParameter("MODIFIED_BY", userInfo.UserName),
                new OracleParameter("MODIFY_IP", userInfo.UserIp)
            });
        }

        public async Task<List<CellPO>> GetTrayCellList(List<string> trayBarcodeList)
        {
            return await dbContext.Set<CellPO>().AsNoTrackingWithIdentityResolution().Where(entity => !string.IsNullOrWhiteSpace(entity.TrayBarcode) && trayBarcodeList.Contains(entity.TrayBarcode)).ToListAsync();
        }
    }
}
